package com.heaven.service.impl;

import com.heaven.core.dao.VideoCategoryDao;
import com.heaven.core.entity.VideoCategoryEntity;
import com.heaven.core.framework.PzServiceImpl;
import com.heaven.customerServer.customerController.vo.videoCategory.TreeNode;
import com.heaven.service.VideoCategoryService;
import com.heaven.utils.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

@Service("videoCategoryService")
public class VideoCategoryServiceImpl extends PzServiceImpl<VideoCategoryDao, VideoCategoryEntity> implements VideoCategoryService {
    @Override
    @Cacheable(value = "videoCategoryTree", key = "#root.methodName")
    public List<TreeNode> listCategoryTree() {
        List<VideoCategoryEntity> videoCategoryEntities = selectList(new Query());
        List<TreeNode> ans = new ArrayList<>();
        videoCategoryEntities.forEach(categoryLevel1 -> {
            TreeNode node1 = new TreeNode();
            node1.setValue(categoryLevel1.getCatId());
            node1.setLabel(categoryLevel1.getName());
            BeanUtils.copyProperties(categoryLevel1, node1);
            node1.setChildren(new ArrayList<>());

            if(categoryLevel1.getChildren() != null) {
                categoryLevel1.getChildren().forEach(categoryLevel2 -> {
                    TreeNode node2 = new TreeNode();
                    node2.setValue(node1.getValue() + "-" + categoryLevel2.getCatId());
                    node2.setLabel(categoryLevel2.getName());
                    BeanUtils.copyProperties(categoryLevel2, node2);
                    node2.setChildren(new ArrayList<>());
                    node1.getChildren().add(node2);

                    if(categoryLevel2.getChildren() != null) {
                        categoryLevel2.getChildren().forEach(categoryLevel3 -> {
                            TreeNode node3 = new TreeNode();
                            node3.setValue(node2.getValue() + "-" + categoryLevel3.getCatId());
                            node3.setLabel(categoryLevel3.getName());
                            BeanUtils.copyProperties(categoryLevel3, node3);
                            node2.getChildren().add(node3);
                        });
                    }
                });
            }
            ans.add(node1);
        });
        return ans;
    }
}
